<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>地址至坐标转换</title>
</head>
<script charset="utf-8" src="https://map.qq.com/api/gljs?v=1.exp&libraries=service&key=FXFBZ-N2XRJ-UWKF2-XLHM3-6RWPJ-5UB7D"></script>
<style type="text/css">
    html,
    body {
        height: 100%;
        margin: 0px;
        padding: 0px;
    }

    #container {
        width: 100%;
        height: 100%;
    }

    #panel {
        position: absolute;
        background: #FFF;
        width:300px;
        padding: 20px;
        z-index: 9999;
        top: 30px;
        left: 30px;
    }
</style>


<body>
    <div id="container"></div>
    <div id="panel">
      <p>请在右侧示例代码第10行填入您的key，并执行查看运行结果（key可在控制台应用管理中自行创建）</p>
        <p><label>地址</label><input id='address' type="text" value='北京市海淀区彩和坊路海淀西大街74号' ><input id="convert" type="button" class="btn" value="转换为坐标" onclick="convert()" /></p>
        <p><label>坐标</label><input id='location' type='text' disabled value='' /></p>
    </div>
</body>

<script type="text/javascript">
var map = new TMap.Map('container', {
  zoom: 14,
  center: new TMap.LatLng(39.986785, 116.301012),
});
var geocoder = new TMap.service.Geocoder(); // 新建一个正逆地址解析类
var markers = new TMap.MultiMarker({
  map: map,
  geometries: [],
});

function convert() {
  markers.setGeometries([]);
  // 将给定的地址转换为坐标位置
  geocoder
    .getLocation({ address: document.getElementById('address').value })
    .then((result) => {
      markers.updateGeometries([
        {
          id: 'main',
          position: result.result.location, // 将得到的坐标位置用点标记标注在地图上
        },
      ]);
      map.setCenter(result.result.location);
      document.getElementById(
        'location'
      ).value = result.result.location.toString();
      // 显示坐标数值
    });
}
</script>

</html>